class NotificationManager {
    constructor() {
        this.toastContainer = null;
        this.alertModal = null;
        this.confirmModal = null;
        this.init();
    }

    init() {
        this.toastContainer = document.getElementById('toastContainer');
        this.alertModal = document.getElementById('alertModal');
        this.confirmModal = document.getElementById('confirmModal');
        this.setupAlertModal();
        this.setupConfirmModal();
    }

    setupAlertModal() {
        const confirmBtn = document.getElementById('alertConfirmBtn');
        confirmBtn?.addEventListener('click', () => {
            this.hideAlert();
        });

        // 点击背景关闭
        this.alertModal?.addEventListener('click', (e) => {
            if (e.target === this.alertModal) {
                this.hideAlert();
            }
        });

        // ESC键关闭
        document.addEventListener('keydown', (e) => {
            if (e.key === 'Escape' && this.alertModal?.classList.contains('show')) {
                this.hideAlert();
            }
        });
    }

    setupConfirmModal() {
        const confirmBtn = document.getElementById('confirmConfirmBtn');
        const cancelBtn = document.getElementById('confirmCancelBtn');
        
        // console.log('[ConfirmModal] 初始化确认对话框');
        // console.log('[ConfirmModal] 确认按钮:', confirmBtn);
        // console.log('[ConfirmModal] 取消按钮:', cancelBtn);
        
        // ESC键关闭
        document.addEventListener('keydown', (e) => {
            if (e.key === 'Escape' && this.confirmModal?.classList.contains('show')) {
                this.hideConfirm();
                if (this.confirmReject) {
                    this.confirmReject(false);
                }
            }
        });
    }

    // 显示Toast提示
    showToast(message, type = 'info', title = '', duration = 4000) {
        const toast = document.createElement('div');
        toast.className = `toast ${type}`;
        
        const iconMap = {
            success: 'fas fa-check',
            error: 'fas fa-times',
            warning: 'fas fa-exclamation-triangle',
            info: 'fas fa-info-circle'
        };

        const titleMap = {
            success: title || '成功',
            error: title || '错误',
            warning: title || '警告',
            info: title || '提示'
        };

        toast.innerHTML = `
            <div class="toast-icon">
                <i class="${iconMap[type]}"></i>
            </div>
            <div class="toast-content">
                <div class="toast-title">${titleMap[type]}</div>
                <div class="toast-message">${message}</div>
            </div>
            <button class="toast-close">
                <i class="fas fa-times"></i>
            </button>
        `;

        // 添加关闭事件
        const closeBtn = toast.querySelector('.toast-close');
        closeBtn.addEventListener('click', () => {
            this.removeToast(toast);
        });

        // 添加到容器
        this.toastContainer.appendChild(toast);

        // 显示动画
        setTimeout(() => {
            toast.classList.add('show');
        }, 10);

        // 自动关闭
        if (duration > 0) {
            setTimeout(() => {
                this.removeToast(toast);
            }, duration);
        }

        return toast;
    }

    // 移除Toast
    removeToast(toast) {
        toast.classList.add('hide');
        setTimeout(() => {
            if (toast.parentNode) {
                toast.parentNode.removeChild(toast);
            }
        }, 300);
    }

    // 显示确认对话框
    showAlert(message, type = 'info', title = '') {
        return new Promise((resolve) => {
            const alertIcon = document.getElementById('alertIcon');
            const alertTitle = document.getElementById('alertTitle');
            const alertMessage = document.getElementById('alertMessage');
            const confirmBtn = document.getElementById('alertConfirmBtn');

            const iconMap = {
                success: { icon: 'fas fa-check-circle', color: '#10b981', bg: '#d1fae5' },
                error: { icon: 'fas fa-times-circle', color: '#ef4444', bg: '#fee2e2' },
                warning: { icon: 'fas fa-exclamation-triangle', color: '#f59e0b', bg: '#fef3c7' },
                info: { icon: 'fas fa-info-circle', color: '#3b82f6', bg: '#dbeafe' }
            };

            const titleMap = {
                success: title || '成功',
                error: title || '错误',
                warning: title || '警告',
                info: title || '提示'
            };

            // 设置图标和样式
            const iconConfig = iconMap[type];
            alertIcon.innerHTML = `<i class="${iconConfig.icon}"></i>`;
            alertIcon.style.color = iconConfig.color;
            alertIcon.style.backgroundColor = iconConfig.bg;

            // 设置内容
            alertTitle.textContent = titleMap[type];
            alertMessage.textContent = message;

            // 显示模态框
            this.alertModal.classList.add('show');

            // 设置确认按钮事件
            const handleConfirm = () => {
                this.hideAlert();
                confirmBtn.removeEventListener('click', handleConfirm);
                resolve(true);
            };

            confirmBtn.addEventListener('click', handleConfirm);
        });
    }

    // 隐藏确认对话框
    hideAlert() {
        this.alertModal?.classList.remove('show');
    }

    // 便捷方法
    success(message, title = '', duration = 4000) {
        return this.showToast(message, 'success', title, duration);
    }

    error(message, title = '', duration = 5000) {
        return this.showToast(message, 'error', title, duration);
    }

    warning(message, title = '', duration = 4000) {
        return this.showToast(message, 'warning', title, duration);
    }

    info(message, title = '', duration = 4000) {
        return this.showToast(message, 'info', title, duration);
    }

    // 替换原生alert的方法
    alert(message, type = 'info', title = '') {
        return this.showAlert(message, type, title);
    }

    // 显示确认对话框
    showConfirm(message, options = {}) {
        return new Promise((resolve, reject) => {
            const {
                title = '确认操作',
                confirmText = '确定',
                cancelText = '取消',
                type = 'warning', // warning, danger, info
                confirmButtonType = 'danger' // danger, primary
            } = options;

            const confirmIcon = document.getElementById('confirmIcon');
            const confirmTitle = document.getElementById('confirmTitle');
            const confirmMessage = document.getElementById('confirmMessage');
            const confirmBtn = document.getElementById('confirmConfirmBtn');
            const cancelBtn = document.getElementById('confirmCancelBtn');

            // 设置图标样式
            confirmIcon.className = `confirm-icon ${type}`;
            const iconMap = {
                warning: 'fas fa-exclamation-triangle',
                danger: 'fas fa-exclamation-circle',
                info: 'fas fa-question-circle'
            };
            confirmIcon.innerHTML = `<i class="${iconMap[type]}"></i>`;

            // 设置内容
            confirmTitle.textContent = title;
            confirmMessage.textContent = message;
            confirmBtn.textContent = confirmText;
            cancelBtn.textContent = cancelText;

            // 设置确认按钮样式
            confirmBtn.className = `confirm-btn confirm-btn-confirm ${confirmButtonType}`;

            // 显示模态框
            this.confirmModal.classList.add('show');

            // 保存resolve和reject函数
            this.confirmResolve = resolve;
            this.confirmReject = reject;

            // 设置按钮事件
            const handleConfirm = () => {
                this.hideConfirm();
                confirmBtn.removeEventListener('click', handleConfirm);
                cancelBtn.removeEventListener('click', handleCancel);
                resolve(true);
            };

            const handleCancel = () => {
                this.hideConfirm();
                confirmBtn.removeEventListener('click', handleConfirm);
                cancelBtn.removeEventListener('click', handleCancel);
                resolve(false);
            };

            confirmBtn.addEventListener('click', handleConfirm);
            cancelBtn.addEventListener('click', handleCancel);

            // 点击背景关闭
            const handleBackgroundClick = (e) => {
                if (e.target === this.confirmModal) {
                    this.hideConfirm();
                    this.confirmModal.removeEventListener('click', handleBackgroundClick);
                    resolve(false);
                }
            };
            this.confirmModal.addEventListener('click', handleBackgroundClick);
        });
    }

    // 隐藏确认对话框
    hideConfirm() {
        this.confirmModal?.classList.remove('show');
    }

    // 便捷的确认方法
    confirm(message, options = {}) {
        return this.showConfirm(message, options);
    }

    // 退出登录确认
    confirmLogout() {
        return this.showConfirm(
            '退出登录后，您的本地数据将被清除。确定要退出登录吗？',
            {
                title: '退出登录',
                confirmText: '退出登录',
                cancelText: '取消',
                type: 'danger',
                confirmButtonType: 'danger'
            }
        );
    }
}

// 创建全局实例
window.notification = new NotificationManager();

// 重写全局confirm函数
window.confirm = function(message) {
    return window.notification.confirm(message);
};

// 重写全局alert函数
window.alert = function(message) {
    return window.notification.alert(message);
};